package com.yx.controller;

import com.alibaba.fastjson.JSON;
import com.yx.constatns.AuthConstatns;
import com.yx.feign.api.UserService;
import com.yx.vo.Customer;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Classname RestAuthController
 * @Date 2021/07/15 20:28
 * @Author by yx
 * @Description TODO:
 */
@RestController
@RequestMapping("/oauth")
@Slf4j
public class RestAuthController {
    @Autowired
    private UserService userService;

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        //1.获取应用信息
        AuthRequest authRequest = getAuthRequest();
        //2.引导进入第三方授权页面
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback, HttpSession session) {
        log.debug("百度认证成功返回了code:" + callback.getCode());
        AuthRequest authRequest = getAuthRequest();
        //1.根据code获取AccessToken
        AuthResponse authResponse = authRequest.login(callback);

        //2.判断授权是否成功
        if (authResponse.ok()) {
            //认证授权成功--->返回对象为AuthUser
            AuthUser authUser = (AuthUser)authResponse.getData();

            log.debug("username:{}", authUser.getUsername());
            log.debug("getUuid:{}", authUser.getUuid());
            log.debug("getEmail:{}", authUser.getEmail());
            log.debug("getAvatar:{}", authUser.getAvatar());

            //判断用户是否是第一次登录
            String uuid = authUser.getUuid();
            Customer customer = userService.getUserByOauthId(uuid);
            if (customer==null){
                //第一次登录,需要注册
                customer = new Customer();
                customer.setUsername(authUser.getUsername());
                customer.setOauthId(authUser.getUuid());
                userService.addUser(customer);
            }

            //把当前登录用户的session存入redis中
            session.setAttribute(AuthConstatns.AUTH_SESSION, customer);
            return "认证成功:"+ JSON.toJSONString(customer);
        }else {
            // 认证授权失败
            return "认证授权失败";
        }
    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("2c1vR1kUwjVIafq6WpgjG24S")
                .clientSecret("D0GSxywYaiXW6eMm5FG44TjeGwYEbllS")
                .redirectUri("http://localhost/auth/oauth/callback")
                .build());
    }
}
